package cn.whit.blog.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import cn.whit.blog.domain.Article;
import cn.whit.blog.domain.StatisticalType;
import cn.whit.blog.domain.Tblog;
import cn.whit.blog.domain.Tblogtype;
import cn.whit.blog.domain.User;
import cn.whit.blog.service.TblogService;
import cn.whit.blog.service.TblogtypeService;
import cn.whit.blog.service.TcommitService;
import cn.whit.blog.util.BeanFactory;
import cn.whit.blog.util.DynamicQuery;
import cn.whit.blog.util.JsonUtils;
import cn.whit.blog.util.PageModel;
import cn.whit.blog.util.Parameter;
import cn.whit.blog.util.PropertyUtil;
import cn.whit.blog.util.SolrUtil;
import cn.whit.blog.util.UploadUtils;

public class TblogServlet extends BaseServlet {

	private static final long serialVersionUID = -3061142824111882302L;

	TblogService tblogService = (TblogService) BeanFactory.createObject("tblogService");
	
	TcommitService tcommitService = (TcommitService) BeanFactory.createObject("tcommitService");
	
	TblogtypeService tblogtypeService = (TblogtypeService) BeanFactory.createObject("tblogtypeService");
	
	//个人中心
	public String personal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//用户自己的博客
		String num = request.getParameter("num");
		String tblogtypeid = request.getParameter("tblogtypeid");
		if (num == null) {
			num = "1";
		}
		// 获取当前页
		int curNum = Integer.parseInt(num);
		int pageSize = 5;
		DynamicQuery query = new DynamicQuery();
		User loginUser = (User) request.getAttribute("loginUser");
		if(loginUser != null) {
			query.addParameter(new Parameter("userid", "=", loginUser.getId()));
		}
		
		if (tblogtypeid != null && !("".equals(tblogtypeid)) && !("all".equals(tblogtypeid))) {
			// 查询参数如果要验证数据类型等，在这里执行
			query.addParameter(new Parameter("tblogtypeid", "like", "%" + tblogtypeid + "%"));
			request.setAttribute("tblogtypeid", tblogtypeid);
		}else {
			request.setAttribute("tblogtypeid","all");
		}
		//查询用户自己的博客列表，发布时间顺序倒序（最新的在前面，分页显示）
		PageModel pm  = tblogService.findByPageAndQuery(curNum,  pageSize,  query);
		//对显示在首页博客列表中的博客的正文内容，截取前600个字符
		List<Tblog> blist = pm.getList();
		for(Tblog tblog : blist) {
			if(tblog.getContent().length() > 600) {
				tblog.setContent(tblog.getContent().substring(0, 600)+"...");
			}
		}
		
		pm.setUrl("TblogServlet?method=personal");
		request.setAttribute("page", pm);
		
		//博客类型
		List<Tblogtype> ones = tblogtypeService.findAll();
		request.setAttribute("list", ones);
		
		return "/view/personal/list.jsp";
	}
	
	//管理员批量删除数据
	public String delete(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
		
		System.out.println(request.getParameter("ids"));
		String ids = request.getParameter("ids");
		
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		if(ids != null) {
			String[] split = ids.split(",");
			System.out.println(split.length);
			for(String s: split) {
				System.out.println(s);
				tblogService.deleteById(s);
			}
			writer.write("删除成功".toString());
			return null;
		}
		writer.write("删除失败，请联系管理员".toString());
		return null;
	}
	
	//用户前端删除自己的博客
	public String deleteByWriter(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
		//
		//判断删除动作是当前博客的作者或者是管理员身份：
		String blogid = request.getParameter("blogid");
		
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		if(blogid != null) {
			Tblog one = tblogService.findById(blogid);
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if(one != null && loginUser !=null && loginUser.getId().equals(one.getUserid())) {
				//是作者本人执行删除
				tblogService.deleteById(blogid);
				writer.write("删除成功".toString());
				return null;
			}
			
		}
		writer.write("删除失败，请联系管理员".toString());
		return null;
	}
	
	//点赞 
	public String addvote(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		Map<String, String> map = JsonUtils.getJsonMap(request);
        
		String type = map.get("type");
		System.out.println("type=" + type);
		String kitty = map.get("kitty");
		System.out.println("kitty=" + kitty);
		String id = map.get("id");
		System.out.println("id=" + id);
		
		PrintWriter out = response.getWriter();
		
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if(loginUser == null) {
			tblogService.addvote(id, "0" ,"访客", StatisticalType.Dianzan);
		}else {
			tblogService.addvote(id, loginUser.getId() ,loginUser.getName(), StatisticalType.Dianzan);
		}
		
		
		out.write("okokokok");
		return null;
	}

	//写博客
	public String newBlog(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//博客类型
		List<Tblogtype> ones = tblogtypeService.findAll();
		request.setAttribute("list", ones);
		return "/view/blog/newBlog.jsp";
	}
	
	//显示详情
	public String show(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String num = request.getParameter("num");
		if (num == null) {
			num = "1";
		}
		// 该博客的评论的分页处理 获取当前页
		int curNum = Integer.parseInt(num);
		int pageSize = 5;
		
		System.out.println("id=" + id);
		
		Tblog tblog = tblogService.findById(id);
		
		request.setAttribute("item", tblog);
		
		//该博客相关的评论数据
		DynamicQuery query = new DynamicQuery();;
		PageModel pm = tcommitService.findAllByBlogIdWithPageAndQuery(curNum, pageSize, query,id);
		pm.setUrl("TblogServlet?method=show&id=" + id);
		request.setAttribute("page", pm);
		String picpath = PropertyUtil.getProperty("picpath");
		request.setAttribute("picpath", picpath);
		return "/view/blog/showBlog.jsp";
	}
	
	//去博客首页,用户前台
	public String index(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String num = request.getParameter("num");
		String tblogtypeid = request.getParameter("tblogtypeid");
		System.out.println("tblogtypeid=" + tblogtypeid);
		if (num == null) {
			num = "1";
		}
		// 获取当前页
		int curNum = Integer.parseInt(num);
		int pageSize = 5;
		DynamicQuery query = new DynamicQuery();
		if (tblogtypeid != null && !("".equals(tblogtypeid)) && !("all".equals(tblogtypeid))) {
			// 查询参数如果要验证数据类型等，在这里执行
			query.addParameter(new Parameter("tblogtypeid", "like", "%" + tblogtypeid + "%"));
			request.setAttribute("tblogtypeid", tblogtypeid);
		}else {
			request.setAttribute("tblogtypeid","all");
		}
		//查询所有博客列表，发布时间顺序倒序（最新的在前面，分页显示）
		PageModel pm  = tblogService.findByPageAndQuery(curNum,  pageSize,  query);
		//对显示在首页博客列表中的博客的正文内容，截取前600个字符
		List<Tblog> blist = pm.getList();
		for(Tblog tblog : blist) {
			if(tblog.getContent().length() > 600) {
				tblog.setContent(tblog.getContent().substring(0, 600)+"...");
			}
		}
		
		pm.setUrl("TblogServlet?method=index");
		request.setAttribute("page", pm);
		
		//博客类型
		List<Tblogtype> ones = tblogtypeService.findAll();
		request.setAttribute("list", ones);
		return "/view/main/index.jsp";
	}
	
	//管理员后台
	public String tblogList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// num是传入的当前页
		String num = request.getParameter("num");
		String tblogtypeid = request.getParameter("tblogtypeid");
		System.out.println(tblogtypeid);
		if (num == null) {
			num = "1";
		}
		// 获取当前页
		int curNum = Integer.parseInt(num);
		int pageSize = 5;
		DynamicQuery query = new DynamicQuery();
		if (tblogtypeid != null && !("".equals(tblogtypeid)) && "all".equals(tblogtypeid)) {
			// 查询参数如果要验证数据类型等，在这里执行
			query.addParameter(new Parameter("tblogtypeid", "like", "%" + tblogtypeid + "%"));
			request.setAttribute("tblogtypeid", tblogtypeid);
		}
		PageModel pm = tblogService.findByPageAndQuery(curNum, pageSize, query);
		request.setAttribute("page", pm);
		
		//博客类型
		List<Tblogtype> ones = tblogtypeService.findAll();
		request.setAttribute("list", ones);
		return "/jsp/blog/blogList.jsp";
	}

	// hello
	public String hello(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 请求转发
		return "/jsp/hello.jsp";
	}

	// 新增博客 
	public String add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// 存储表单中数据
		Map<String, String> map = new HashMap<String, String>();
		Tblog tblog = new Tblog();
		try {
			// 利用req.getInputStream();获取到请求体中全部数据,进行拆分和封装
			DiskFileItemFactory fac = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fac);
			List<FileItem> list = upload.parseRequest(request);
			// 4_遍历集合
			for (FileItem item : list) {
				if (item.isFormField()) {
					// 5_如果当前的FileItem对象是普通项
					// 将普通项上name属性的值作为键,将获取到的内容作为值,放入MAP中
					// {username<==>tom,password<==>1234}
					map.put(item.getFieldName(), item.getString("utf-8"));
				} else {
					// 6_如果当前的FileItem对象是上传项
					// 获取到原始的文件名称
					String oldFileName = item.getName();
					System.out.println("原始文件的名字是：" + oldFileName);
					// 获取到要保存文件的名称 1222.doc 123421342143214.doc
					String newFileName = UploadUtils.getUUIDName(oldFileName);
					long fileSize = item.getSize();
					System.out.println("fileSize:" + fileSize);
					// 通过FileItem获取到输入流对象,通过输入流可以获取到图片二进制数据
					InputStream is = item.getInputStream();
					String realPath = "";
					// realPath 在服务商上，需要取得绝对路径
					realPath = PropertyUtil.getProperty("uploadPath");
					String dir = UploadUtils.getDir(newFileName); // /f/e/d/c/4/9/8/4
					String path = realPath + dir; 
					
					// 内存中声明一个目录
					File newDir = new File(path);
					if (!newDir.exists()) {
						newDir.mkdirs();
					}
					// 在服务端创建一个空文件(后缀必须和上传到服务端的文件名后缀一致)
					File finalFile = new File(newDir, newFileName);
					if (!finalFile.exists()) {
						finalFile.createNewFile();
					}
					// 建立和空文件对应的输出流
					OutputStream os = new FileOutputStream(finalFile);
					// 将输入流中的数据刷到输出流中
					IOUtils.copy(is, os);
					// 释放资源
					IOUtils.closeQuietly(is);
					IOUtils.closeQuietly(os);
					map.put("picurls",  dir + "/"+ newFileName);
				}
			}

			// 7_利用BeanUtils将MAP中的数据填充到Product对象上
			BeanUtils.populate(tblog, map);
			tblog.setPublishTime(new Date());
			tblog.setUpdateTime(new Date());
			tblog.setStatus(0);
			
			//设置当前登录人的userid
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			tblog.setUserid(loginUser.getId());
			tblog.setUsername(loginUser.getName());

			// 8_调用servcie_dao将user上携带的数据存入数据仓库,重定向到查询全部商品信息路径
			long newID = tblogService.save(tblog);
			 
			if(newID != 0) {
				//新增数据成功
				//在solr中建立该博客数据的索引数据
				Article article = new Article();
				article.setId(String.valueOf(newID));
				article.setTitle(tblog.getTitle());
				article.setContent(tblog.getContent());
				article.setAuthor(tblog.getUsername());
				SolrUtil.addIndex(article);
			}else {
				System.out.println("新增博客数据失败");
			}
			
			response.sendRedirect("TblogServlet?method=index");

		} catch (Exception e) {
			e.printStackTrace();
			//保存有异常的处理，跳转到新增页面，给出出错信息 todo
		}

		return null;

		
	}
	public static void main(String[] args) {
		Properties properties = new Properties();
		InputStream in = null;
		 in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
	}

}
